// 路由鉴权 项目中什么情况下可以访问 什么情况下不可以访问
import router from "./router";
import nprogress from 'nprogress'
import setting from "./setting";
import "nprogress/nprogress.css"
import useUserStore from "./store/modules/user";
// 因为在组件外部无法访问小仓库 所以要引入大仓库
import pinia from "./store";
let userStore = useUserStore(pinia)
// 去掉加载的圆圈
nprogress.configure({showSpinner:false})
// 全局的前置守卫
router.beforeEach(async(to:any,from:any,next:any)=>{
    document.title = setting.title + '-' +  to.meta.title
    nprogress.start()
    // 获取token 判断登陆与否
    let token = userStore.token
    let username = userStore.username
    if(token){
        if(to.path == '/login'){
            next({path:'/home'})
        }else{
            if(username){
                next()
            }else{
                // 如果没有用户信息 在守卫这里发请求获取到了用户信息再放行
                try{
                    await userStore.userInfo()
                    next()
                }catch(error){
                    // token失效
                    // 用户手动修改本地存储的token
                    // 退出登录
                    await userStore.userLogout()
                    next({path:'/login',query:{redirect:to.path}})
                }
            }
        }
    }else{
        if(to.path == '/login'){
            next()
        }else{
            next({path:'/login',query:{redirect:to.path}})
        }
    }
})


// 全局的后置守卫
router.afterEach((to:any,from:any)=>{
    nprogress.done()
})